package com.haoqizhe.kernel.shiro.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.haoqizhe.kernel.jwt.utils.JwtTokenUtil;
import com.haoqizhe.kernel.redis.common.util.RedisUtil;
import com.haoqizhe.kernel.shiro.jwt.JwtCredentialsMatcher;
import com.haoqizhe.kernel.shiro.jwt.JwtFilter;
import com.haoqizhe.kernel.shiro.jwt.JwtRealm;
import com.haoqizhe.kernel.shiro.properties.ShiroProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro 权限认证 配置
 * jwt
 *
 * @author haoqizhe.li
 * @date 2018/7/4
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties({ShiroProperties.class})
public class ShiroConfig {

    /**
     * JWT过滤器名称
     */
    private static final String JWT_FILTER_NAME = "jwtFilter";

    /**
     * 登出过滤器
     */
    private static final String LOGOUT_FILTER_NAME = "logout";

    /**
     * Shiro过滤器名称
     */
    private static final String SHIRO_FILTER_NAME = "shiroFilter";

    /**
     * anon
     */
    private static final String ANON = "anon";


    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager shiroSecurityManager, ShiroProperties shiroProperties, RedisUtil redisUtil, JwtTokenUtil jwtTokenUtil) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(shiroSecurityManager);

        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        if (StrUtil.isNotBlank(shiroProperties.getLoginUrl())) {
            shiroFilterFactoryBean.setLoginUrl(shiroProperties.getLoginUrl());
        }

        // 登录成功后要跳转的链接
        if (StrUtil.isNotBlank(shiroProperties.getSuccessUrl())) {
            shiroFilterFactoryBean.setSuccessUrl(shiroProperties.getSuccessUrl());
        }

        // 未授权界面;
        if (StrUtil.isNotBlank(shiroProperties.getUnauthorizedUrl())) {
            shiroFilterFactoryBean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl());
        }

        shiroFilterFactoryBean.setFilters(filters(shiroProperties, redisUtil, jwtTokenUtil));
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap(shiroProperties));
        return shiroFilterFactoryBean;
    }

    @Bean
    public SessionStorageEvaluator sessionStorageEvaluator() {
        DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultWebSessionStorageEvaluator();

        // 关闭session
        sessionStorageEvaluator.setSessionStorageEnabled(false);
        return sessionStorageEvaluator;
    }

    @Bean
    public DefaultSubjectDAO subjectDAO() {
        DefaultSubjectDAO defaultSubjectDAO = new DefaultSubjectDAO();
        defaultSubjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator());
        return defaultSubjectDAO;
    }

    @Bean
    public CredentialsMatcher credentialsMatcher() {
        return new JwtCredentialsMatcher();
    }

    @Bean
    public JwtRealm jwtRealm(ShiroProperties shiroProperties, RedisUtil redisUtil, JwtTokenUtil jwtTokenUtil) {
        JwtRealm jwtRealm = new JwtRealm(shiroProperties, redisUtil, jwtTokenUtil);
        jwtRealm.setCachingEnabled(false);
        jwtRealm.setCredentialsMatcher(credentialsMatcher());
        return jwtRealm;
    }


    @Bean(name = "shiroSecurityManager")
    public SecurityManager securityManager(ShiroProperties shiroProperties, RedisUtil redisUtil, JwtTokenUtil jwtTokenUtil) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(jwtRealm(shiroProperties, redisUtil, jwtTokenUtil));
        securityManager.setSubjectDAO(subjectDAO());

        SecurityUtils.setSecurityManager(securityManager);
        return securityManager;
    }

    @Bean
    public FilterRegistrationBean delegatingFilterProxy() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetFilterLifecycle(true);
        proxy.setTargetBeanName(SHIRO_FILTER_NAME);
        filterRegistrationBean.setFilter(proxy);
        filterRegistrationBean.setAsyncSupported(true);
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
        return filterRegistrationBean;
    }

    @Bean
    public Authenticator authenticator(ShiroProperties shiroProperties, RedisUtil redisUtil, JwtTokenUtil jwtTokenUtil) {
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
        authenticator.setRealms(Arrays.asList(jwtRealm(shiroProperties, redisUtil, jwtTokenUtil)));
        authenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
        return authenticator;
    }

    /**
     * Enabling Shiro Annotations
     *
     * @return
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager shiroSecurityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(shiroSecurityManager);
        return authorizationAttributeSourceAdvisor;
    }

    protected Map<String, String> filterChainDefinitionMap(ShiroProperties shiroProperties) {
        // 拦截器.
        Map<String, String> map = new LinkedHashMap<String, String>();

        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        map.put(shiroProperties.getLogout(), "logout");

        // 配置不会被拦截的链接 顺序判断
        if (CollUtil.isNotEmpty(shiroProperties.getAnon())) {
            shiroProperties.getAnon().forEach(anon -> {
                map.put(anon, ANON);
            });

        }

        // <!-- 过滤链定义，从上向下顺序执行，一般将/**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        if (CollUtil.isNotEmpty(shiroProperties.getAuthc())) {
            shiroProperties.getAuthc().forEach(anon -> {
                map.put(anon, JWT_FILTER_NAME);
            });
        }

        return map;
    }

    protected Map<String, Filter> filters(ShiroProperties shiroProperties, RedisUtil redisUtil, JwtTokenUtil jwtTokenUtil) {
        Map<String, Filter> map = new LinkedHashMap<>();
        map.put(JWT_FILTER_NAME, new JwtFilter(jwtTokenUtil, redisUtil, shiroProperties));
        return map;
    }

}
